const fs = require("fs");
const uuid = require("uuid/v1");
const glob = require("glob");
const path = require("path");
const chalk = require("chalk");
const moment = require("moment");
const mongoose = require("mongoose");
const { promisify } = require("util");
const { logPath, staticHost } = require("./env");
const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);

// 遍历文件
const globPath = p => {
	return new Promise((resolve, reject) => {
		try {
			let files = glob.sync(path.resolve(__dirname, p));
			return resolve(files);
		} catch (error) {
			return reject(error);
		}
	});
};
// 记录日志
const logger = (type, msg) => {
	console.log(chalk.green(msg));
	let fileName = `log-${type}-${moment().format("YYYYMMDD")}`;
	let filePath = `${path.resolve(logPath)}/${fileName}`;
	msg = `[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${msg} \n`;
	fs.appendFile(filePath, msg, err => {
		if (err) console.log(chalk.red(`[日志写入错误]  ${err} \n`));
	});
};
// 打印日志
const log = (color = "green", msg) => {
	console.log(chalk[color](msg));
};
// rest实体
class Resp {
	constructor(code, msg, data = null) {
		this.code = code;
		this.msg = msg;
		this.data = data;
	}
}
// 验证objectId
const validObjectId = ids => {
	let valid = mongoose.Types.ObjectId.isValid;
	let isValid = true;
	if (!(ids instanceof Array)) ids = [ids];
	ids.forEach(id => {
		if (!valid(id)) isValid = false;
	});
	return isValid;
};

// 递归读取文件夹信息 id parentId 模式
const readDir = async (prePath, path = "", showLink = true, parentId = "") => {
	let filesArr = [];
	const files = await readdir(prePath + "/" + path);
	if (!files || files.length === 0) return null;
	for (let i = 0; i < files.length; i++) {
		const istat = await stat(prePath + path + "/" + files[i]);
		const id = uuid().split("-").join("");
		const file = {
			id: id,
			type: "file",
			name: files[i],
			parentId: parentId,
			birthtime: istat.birthtime
		};
		if (istat.isDirectory()) {
			file.type = "dir";
			file.parentId = parentId;
			let childrenArr = await readDir(prePath, `${path}/${files[i]}`, showLink, id);
			filesArr = filesArr.concat(childrenArr);
		} else {
			if (showLink) file.link = `${staticHost}${path}/${file.name}`;
		}
		filesArr.push(file);
	}
	return filesArr;
};

module.exports = {
	globPath,
	log,
	logger,
	Resp,
	validObjectId,
	readDir
};
